import aesjs from 'aes-js'
import { Base64 } from 'js-base64';// 为了多端兼容性问题，所以引入了Base64库，如果只兼容h5端，可以使用window.btoa


function _arrayBufferToBase64(buffer) {
  let binary = '';
  const bytes = new Uint8Array(buffer);
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  const result = Base64.btoa(binary);   
  return result;
}

/**
 * 对文本进行加密
 * @param {Object} text 需要加密的文本
 */
export function encrpy(text) {
  const key = [119, 242, 211, 219, 137, 201, 138, 145, 65, 222, 145, 171, 213, 17, 129, 200];
  const textBytes = aesjs.utils.utf8.toBytes(text);
  //ecb方式
  const ecb = new aesjs.ModeOfOperation.ecb(key);
  //加密，使用pkcs7填充
  const encryptedBytes = ecb.encrypt(aesjs.padding.pkcs7.pad(textBytes));
  //加密后的bytes
  console.log(encryptedBytes);
  //加密后bytes转base64
  const encryptedBase64Str = _arrayBufferToBase64(encryptedBytes);
  return encryptedBase64Str
}
